package com.mysoft.gfyx.workbench.subscriber;

import com.fasterxml.jackson.core.type.TypeReference;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.framework.common.util.JsonUtil;
import com.mysoft.framework.context.api.ContextManager;
import com.mysoft.framework.event.annotation.Subscriber;
import com.mysoft.framework.event.api.EventSubscriber;
import com.mysoft.framework.event.enums.EventResultEnum;
import com.mysoft.framework.event.info.EventArgument;
import com.mysoft.framework.event.info.Result;
import com.mysoft.gfyx.common.dto.SystemQueryUserBusinessUnit.QueryUserListResponseDto;
import com.mysoft.gfyx.common.dto.RequestDto;
import com.mysoft.gfyx.common.util.LogUtil;
import com.mysoft.gfyx.common.util.QueryParamUtil;
import com.mysoft.gfyx.workbench.remoteservice.RemoteSystemOrganizationService;
import com.mysoft.gfyx.workbench.service.ProfitService;
import com.mysoft.gfyx.workbench.service.dto.CheckUserAdditionResponseDto;
import com.mysoft.gfyx.workbench.subscriber.dto.UserWrapperDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.management.remote.NotificationResult;
import java.text.ParseException;
import java.util.Objects;

@Slf4j
@Subscriber(name = "Java-profit 新增用户订阅")
public class CreateUserEventSubscriber extends EventSubscriber<UserWrapperDto, NotificationResult> {

    @Autowired
    private ProfitService profitService;

    @Autowired
    private ContextManager contextManager;

    @Autowired
    private LogUtil logUtil;

    @Autowired
    private RemoteSystemOrganizationService remoteSystemService;

    @Override
    public Result<NotificationResult> subscribe(UserWrapperDto message) {
        logUtil.info("用户新增事件", JsonUtil.toString(message));

        // 1, 调用用户的数据，检查用户手机号是唯一判断校验
        String mobile = "";
        String userId = "";

        if (message.getMainEntity() != null) {
            mobile = message.getMainEntity().getMobilePhone();
            userId = message.getMainEntity().getUserGUID().toString();
        }

        // 1, 调用用户的数据，检查用户手机号是唯一判断校验
        String[] selectFields = {"UserId", "UserName", "MobilePhone"};
        String[][] conditions = {{"eq", "MobilePhone", mobile}};
        RequestDto requestDto = QueryParamUtil.BuildRequestDto(selectFields, conditions, 0, 1000);
        QueryUserListResponseDto allUser = remoteSystemService.GetAllUsers(requestDto);

        for (QueryUserListResponseDto.QueryUser user : allUser.getResults()) {
            if (Objects.equals(user.getMobilePhone(), mobile) && !Objects.equals(user.getUserGUID(), userId)) {
                throw new BusinessLogicException("手机号不允许重复，" + mobile + "，已被用户【" + user.getUserName() + "】使用，请更换新的手机号再尝试操作！");
            }
        }

        // 2, mysoft 租户不参与判断
        String tenantCode = contextManager.fetchContextInfo().getTenantCode();

        if (Objects.equals(tenantCode, "Mysoft") || Objects.equals(tenantCode, "mysoft")) {
            logUtil.info("用户事件", "MYSOFT 租户不限制用户");
        } else {
            CheckUserAdditionResponseDto checkUserAdditionResponseDto = null;
            try {
                checkUserAdditionResponseDto = profitService.checkUserAddition();
            } catch (ParseException e) {
                logUtil.info("用户事件", "调用云采购会员接口失败或格式错误:"+e.getMessage());
            }
            if (checkUserAdditionResponseDto.isOverLimitation()) {
                throw new BusinessLogicException("授权用户数共" + checkUserAdditionResponseDto.getMaxUserNumber() + "个，当前已添加用户" + checkUserAdditionResponseDto.getExistUserNumber() + "个，无法继续添加");
            }
        }
        // 返回Fail的话，前端会重点，但是会报找不到对象错误
        // return new Result(EventResultEnum.FAIL);
        // 返回结果，不阻碍流程
        return new Result(EventResultEnum.SUCCESS);
    }

    @Override
    public TypeReference<EventArgument<UserWrapperDto, NotificationResult>> getMessageType() {
        return new TypeReference<EventArgument<UserWrapperDto, NotificationResult>>() {
        };
    }

}